#include "Logger.h"
#include "TcpServer.h"
#include <functional>
#include <string>

using namespace std::placeholders;

class EchoServer {
  public:
    EchoServer(EventLoop *loop, const InetAddress &addr,
               const std::string &name)
        : loop_(loop), server_(loop, addr, name) {
        server_.setConnectionCallback(
            std::bind(&EchoServer::onConnection, this, _1));
        server_.setMessageCallback(
            std::bind(&EchoServer::onMessage, this, _1, _2, _3));
        server_.setThreadNum(1);
    }
    void start() {
        server_.start();
        (void)loop_;
    }

  private:
    void onConnection(const TcpConnectionPtr &conn) {
        if (conn->connected()) {
            LOG_INFO("conn up : %s", conn->peerAddress().toIpPort().c_str());
        } else {
            LOG_INFO("conn down : %s", conn->peerAddress().toIpPort().c_str());
        }
    }
    void onMessage(const TcpConnectionPtr &conn, Buffer *buf, Timestamp time) {
        (void)time;
        std::string msg = buf->retrieveAllAsString();
        conn->send(msg);
        // conn->shutdown(); // 关闭写端，触发EPOLLHUP => closeCallback_
    }

  private:
    EventLoop *loop_;
    TcpServer server_;

}; // class EchoServer

int main() {
    EventLoop loop;
    InetAddress addr(8000);
    EchoServer server(&loop, addr, "EchoServer01");
    server.start();
    loop.loop();
    return 0;
}
